<template>
  <view class="pk-container">
    <!-- 背景层 -->
    <view class="bg-layer"></view>
    
    <!-- 主要内容 -->
    <view class="pk-content">
      <!-- 匹配等待状态 -->
      <view v-if="!pkStarted && !showResult" class="state-card waiting">
        <view v-if="matching" class="matching-section">
          <!-- 圆形倒计时按钮 -->
          <view class="countdown-circle">
            <text class="countdown-text" :class="{ 'countdown-animate': countdownAnimating }">
              {{ countdown }}
            </text>
            <view class="pulse-ring"></view>
            <view class="pulse-ring delay-1"></view>
            <view class="pulse-ring delay-2"></view>
          </view>
          <text class="matching-text">寻找对手中...</text>
          <text class="tip">系统正在为您匹配水平相近的对手</text>
          <button class="cancel-btn" @click="cancelMatch">取消匹配</button>
        </view>
        <view v-else class="start-section">
          <image class="pk-icon" src="/static/icons/pk.png" mode="aspectFit"></image>
          <text class="title">知识PK对战</text>
          <text class="subtitle">挑战随机对手，赢取积分奖励</text>
          <!-- 圆形开始匹配按钮 -->
          <button class="start-btn" @click="startRandomMatch">
            <text>开始匹配</text>
          </button>
        </view>
      </view>

      <!-- 答题状态 -->
      <view v-if="pkStarted && !showResult" class="state-card question-section">
        <view class="opponent-info">
          <image class="avatar" :src="opponent.avatar || '/static/default-avatar.png'"></image>
          <text class="name">VS {{ opponent.name }}</text>
        </view>
        
        <view class="progress-bar">
          <view class="progress" :style="{width: `${(currentQuestionIndex+1)/questions.length*100}%`}"></view>
          <text class="progress-text">{{ currentQuestionIndex+1 }}/{{ questions.length }}</text>
        </view>
        
        <swiper :current="currentQuestionIndex" @change="swiperChange" class="swiper">
          <swiper-item v-for="(question, index) in questions" :key="question._id">
            <view class="question-card">
              <text class="question-content">{{ question.content }}</text>
              <radio-group @change="selectAnswer($event, index)">
                <label v-for="(option, i) in question.options" :key="i" class="option">
                  <radio :value="String(i)" :checked="answers[index] === String(i)" color="#4a90e2" />
                  <text class="option-text">{{ String.fromCharCode(65+i) }}. {{ option }}</text>
                </label>
              </radio-group>
            </view>
          </swiper-item>
        </swiper>
        
        <view class="action-buttons">
          <button class="submit-btn" :disabled="submitting || answers.includes('')" @click="submitPkAnswers">
            <text v-if="!submitting">提交答案</text>
            <view v-else class="loading">
              <view class="mini-spinner"></view>
              <text>提交中</text>
            </view>
          </button>
          <button class="cancel-btn" @click="cancelPk">退出比赛</button>
        </view>
      </view>

      <!-- 结果状态 -->
      <view v-if="showResult" class="state-card result-section">
        <view class="result-content" :class="resultClass">
          <image class="result-icon" :src="resultIcon" mode="aspectFit"></image>
          <text class="result-title">{{ resultTitle }}</text>
          <text class="result-message">{{ resultMessage }}</text>
          
          <view class="score-board">
            <view class="score-item you">
              <text class="label">你</text>
              <text class="score">{{ myScore }}分</text>
            </view>
            <view class="vs">VS</view>
            <view class="score-item opponent">
              <text class="label">{{ opponent.name }}</text>
              <text class="score">{{ opponentScore }}分</text>
            </view>
          </view>
          
          <view class="points-earned" v-if="pointsEarned > 0">
            <uni-icons type="diamond" size="16" color="#FFD700"></uni-icons>
            <text>+{{ pointsEarned }}积分</text>
          </view>
        </view>
        
        <button class="back-btn" @click="resetPk">返回首页</button>
      </view>
    </view>
  </view>
</template>

  <script>
  export default {
    data() {
      return {
        user: {},
        pkStarted: false,
        waitingForOpponent: false,
        matching: false,
        countdown: 30,
        opponent: { name: '未知' },
        opponentId: '',
        questions: [],
        answers: [],
        myScore: 0,
        pk_id: '',
        submitting: false,
        showResult: false,
        resultMessage: '',
        showInputModal: false,
        timer: null,
        currentQuestionIndex: 0,
        lastToast: 0,
        pendingChallenges: []
      };
    },
    onLoad() {
      this.loadUserData();
    },
    onShow() {
      this.getUserPoints();
    },
    onUnload() {
      this.clearTimer();
    },
	watch: {
	    countdown(newVal, oldVal) {
	      if (newVal !== oldVal) {
	        this.animateCountdown();
	      }
	    }
	  },
    methods: {
      loadUserData() {
        this.user = uni.getStorageSync('user') || {};
        if (!this.user.id) {
          uni.navigateTo({ url: '/pages/student/login' });
        }
        console.log('用户ID:', this.user.id); // 调试
      },
	  animateCountdown() {
	        this.countdownAnimating = true;
	        setTimeout(() => {
	          this.countdownAnimating = false;
	        }, 500);
	      },
      async getUserPoints() {
        try {
          const res = await uniCloud.callFunction({
            name: 'getUserPoints',
            data: { user_id: this.user.id }
          });
          if (res.result.code === 0) {
            this.user.points = res.result.data.points;
            uni.setStorageSync('user', this.user);
          }
        } catch (e) {
          console.error('获取积分失败:', e);
        }
      },
      showOpponentInput() {
        this.showInputModal = true;
        this.opponentId = '';
      },
      async startRandomMatch() {
        try {
          const res = await uniCloud.callFunction({
            name: 'startPk',
            data: { user_id: this.user.id, mode: 'random' }
          });
          if (res.result.code === 0) {
            this.matching = true;
            this.pk_id = res.result.data.pk_id;
            this.startCountdown();
            this.checkPkStatus();
          } else {
            this.showToast({ title: res.result.msg, icon: 'none' });
          }
        } catch (e) {
          this.showToast({ title: '发起匹配失败', icon: 'none' });
        }
      },
      startCountdown() {
        this.countdown = 30;
        this.timer = setInterval(() => {
          this.countdown--;
          if (this.countdown <= 0) {
            this.clearTimer();
            this.matching = false;
            this.showToast({ title: '匹配超时', icon: 'none' });
            this.cancelMatch();
          }
        }, 1000);
      },
      clearTimer() {
        if (this.timer) {
          clearInterval(this.timer);
          this.timer = null;
        }
      },
      async cancelMatch() {
        try {
          if (!this.pk_id) {
            this.matching = false;
            this.clearTimer();
            this.resetPk();
            this.showToast({ title: '已取消匹配', icon: 'none' });
            return;
          }
          const res = await uniCloud.callFunction({
            name: 'cancelPk',
            data: { pk_id: this.pk_id, user_id: this.user.id }
          });
          if (res.result.code === 0) {
            this.matching = false;
            this.clearTimer();
            this.resetPk();
            this.showToast({ title: '已取消匹配', icon: 'none' });
          } else {
            this.showToast({ title: res.result.msg, icon: 'none' });
          }
        } catch (e) {
          console.error('取消匹配失败:', e);
          this.matching = false;
          this.clearTimer();
          this.resetPk();
          this.showToast({ title: '取消匹配失败', icon: 'none' });
        }
      },
      selectAnswer(e, index) {
        this.$set(this.answers, index, e.detail.value);
      },
      async submitPkAnswers() {
        if (this.answers.includes('')) {
          this.showToast({ title: '请回答所有题目', icon: 'none' });
          return;
        }
        this.submitting = true;
        try {
          const submitData = this.questions.map((q, i) => ({
            question_id: q._id,
            user_answer: this.answers[i]
          }));
          const res = await uniCloud.callFunction({
            name: 'submitPkAnswers',
            data: { pk_id: this.pk_id, user_id: this.user.id, answers: submitData }
          });
          if (res.result.code === 0) {
            this.myScore = res.result.data.score;
            this.showToast({
              title: `提交成功！答对 ${res.result.data.correctCount} 题，得分 ${res.result.data.score}`,
              icon: 'success'
            });
            this.checkPkStatus();
          } else {
            this.showToast({ title: res.result.msg, icon: 'none' });
          }
        } catch (e) {
          this.showToast({ title: '提交失败', icon: 'none' });
        } finally {
          this.submitting = false;
        }
      },
      swiperChange(e) {
        this.currentQuestionIndex = e.detail.current;
      },
      showToast(options) {
        if (!this.lastToast || Date.now() - this.lastToast > 2000) {
          uni.showToast({
            title: options.title,
            icon: options.icon || 'none',
            duration: 2000
          });
          this.lastToast = Date.now();
        }
      },
      async checkPkStatus() {
        if (!this.pk_id) {
          console.warn('无有效的 PK ID，停止轮询');
          this.clearTimer();
          return;
        }
        this.clearTimer();
        this.timer = setInterval(async () => {
          try {
            const res = await uniCloud.callFunction({
              name: 'getPkStatus',
              data: { pk_id: this.pk_id, user_id: this.user.id }
            });
            if (res.result.code === 0) {
              const { status, winner_id, opponent_score, questions, exited_by } = res.result.data;
              if (status === 'rejected') {
                this.clearTimer();
                this.waitingForOpponent = false;
                this.resetPk();
                this.showToast({ title: '对手已拒绝挑战', icon: 'none' });
              } else if (status === 'accepted' && !this.pkStarted) {
                this.clearTimer();
                this.waitingForOpponent = false;
                this.matching = false;
                this.pkStarted = true;
                this.questions = questions;
                this.opponent = res.result.data.opponent;
                this.answers = new Array(this.questions.length).fill('');
                this.showToast({ title: '比赛开始！', icon: 'success' });
              } else if (status === 'cancelled') {
                this.clearTimer();
                this.matching = false;
                this.resetPk();
                this.showToast({ title: '匹配已取消', icon: 'none' });
              } else if (status === 'completed') {
                this.clearTimer();
                this.pkStarted = false;
                this.showResult = true;
                if (exited_by && exited_by !== this.user.id) {
                  this.resultMessage = `对手已退出！你的分数：${this.myScore}，对手分数：${opponent_score}`;
                } else if (winner_id === this.user.id) {
                  this.resultMessage = `你赢了！你的分数：${this.myScore}，对手分数：${opponent_score}`;
                } else if (winner_id === null) {
                  this.resultMessage = `平局！你的分数：${this.myScore}，对手分数：${opponent_score}`;
                } else {
                  this.resultMessage = `对手获胜！你的分数：${this.myScore}，对手分数：${opponent_score}`;
                }
                this.getUserPoints();
              }
            } else {
              console.warn('PK状态查询失败:', res.result.msg);
              this.clearTimer();
              this.matching = false;
              this.waitingForOpponent = false;
              this.resetPk();
              this.showToast({ title: res.result.msg || 'PK已失效', icon: 'none' });
            }
          } catch (e) {
            console.error('检查PK状态失败:', e);
            this.clearTimer();
            this.matching = false;
            this.waitingForOpponent = false;
            this.resetPk();
            this.showToast({ title: '检查状态失败', icon: 'none' });
          }
        }, 2000);
      },
      resetPk() {
        this.pkStarted = false;
        this.waitingForOpponent = false;
        this.matching = false;
        this.showResult = false;
        this.questions = [];
        this.answers = [];
        this.myScore = 0;
        this.pk_id = '';
        this.opponent = { name: '未知' };
        this.currentQuestionIndex = 0;
        this.clearTimer();
      }
    }
  };
  </script>

  <style scoped>
/* 改进后的CSS */
.pk-container {
  position: relative;
  padding: 20px;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.bg-layer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 40vh;
  background: linear-gradient(135deg, #4a90e2 0%, #5aa1ff 100%);
  z-index: 0;
  border-radius: 0 0 20% 20%;
}

.pk-content {
  width: 100%;
  max-width: 600px;
  z-index: 1;
}

.state-card {
  background: rgba(255,255,255,0.95);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 10px 30px rgba(74, 144, 226, 0.15);
  margin-bottom: 20px;
}

/* 匹配等待状态样式 */
.waiting .start-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 20px 0;
}

.pk-icon {
  width: 100px;
  height: 100px;
  margin-bottom: 16px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.subtitle {
  font-size: 14px;
  color: #666;
  margin-bottom: 24px;
}

.start-btn {
  background: linear-gradient(45deg, #4a90e2, #5aa1ff);
  color: white;
  border: none;
  border-radius: 30px;
  padding: 12px 36px;
  font-size: 16px;
  box-shadow: 0 4px 12px rgba(74, 144, 226, 0.3);
  transition: all 0.3s;
}

.start-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2px 6px rgba(74, 144, 226, 0.3);
}

/* 答题状态样式 */
.opponent-info {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  border: 2px solid rgba(255,255,255,0.8);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.progress-bar {
  height: 6px;
  background: #f0f0f0;
  border-radius: 3px;
  margin-bottom: 20px;
  position: relative;
}

.progress {
  height: 100%;
  background: linear-gradient(90deg, #4a90e2, #5aa1ff);
  border-radius: 3px;
  transition: width 0.3s;
}

.progress-text {
  position: absolute;
  right: 0;
  top: -24px;
  font-size: 12px;
  color: #666;
}

.swiper {
  height: 50vh;
  margin-bottom: 20px;
}

.question-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.question-content {
  font-size: 18px;
  line-height: 1.6;
  margin-bottom: 24px;
  color: #333;
}

.option {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 12px;
  border-radius: 8px;
  background: rgba(0,0,0,0.02);
  transition: all 0.2s;
}

.option:active {
  background: rgba(74, 144, 226, 0.1);
}

.option-text {
  margin-left: 12px;
  font-size: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.submit-btn {
  flex: 1;
  background: linear-gradient(45deg, #4a90e2, #5aa1ff);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px;
  font-size: 16px;
}

.submit-btn:disabled {
  background: #cccccc;
  opacity: 0.7;
}

.cancel-btn {
  flex: 1;
  background: #f0f0f0;
  color: #666;
  border: none;
  border-radius: 8px;
  padding: 12px;
  font-size: 16px;
}

/* 结果状态样式 */
.result-section {
  text-align: center;
}

.result-content {
  padding: 20px 0;
}

.result-icon {
  width: 80px;
  height: 80px;
  margin-bottom: 16px;
}

.result-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.result-message {
  font-size: 16px;
  color: #666;
  margin-bottom: 24px;
}

.score-board {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 24px;
  margin-bottom: 24px;
}

.score-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.label {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.score {
  font-size: 24px;
  font-weight: bold;
}

.you .score {
  color: #4a90e2;
}

.opponent .score {
  color: #ff5252;
}

.vs {
  font-size: 16px;
  color: #999;
}

.points-earned {
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 215, 0, 0.1);
  padding: 8px 16px;
  border-radius: 20px;
  color: #FF9800;
  font-size: 14px;
  margin: 0 auto 24px;
  width: fit-content;
}

.back-btn {
  background: #4a90e2;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  width: 100%;
}

/* 加载动画 */
.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(74, 144, 226, 0.2);
  border-radius: 50%;
  border-top-color: #4a90e2;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

.mini-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255,255,255,0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s linear infinite;
  margin-right: 8px;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
  </style>